import React, {Component} from 'react';
import {AppUi} from "./AppUi";
import store from './store'
import {getChangeInputValue, getAddTodoItemAction, getDelItemAction, getInitListAction} from "./store/actionCreator"
import axios from 'axios'

class App extends Component {
    constructor(props) {
        super(props);
        this.state = store.getState();
        this.handleBtnClick = this.handleBtnClick.bind(this);
        this.handleListClick = this.handleListClick.bind(this);
        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleStoreChange = this.handleStoreChange.bind(this);
        store.subscribe(this.handleStoreChange)
    }

    render() {
        return (
            <div>
                <AppUi
                    inputValue={this.state.inputValue}
                    list={this.state.list}
                    handleInputChange={this.handleInputChange}
                    handleBtnClick={this.handleBtnClick}
                    handleListClick={this.handleListClick}
                />
            </div>
        );
    }

    componentDidMount() {
        axios.get('http://127.0.0.1:8080/list').then((res) => {
            const action = getInitListAction(res.data);
            store.dispatch(action)
        });
    }

    handleBtnClick() {
        if (this.state.inputValue === '') return;
        const action = getAddTodoItemAction();
        store.dispatch(action)
    }

    handleListClick(index) {
        const action = getDelItemAction(index);
        store.dispatch(action)
    }

    handleInputChange(e) {
        const action = getChangeInputValue(e.target.value);
        store.dispatch(action)
    }

    handleStoreChange() {
        this.setState(store.getState())
    }
}

export default App;
